package org.stephen.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.stephen.config.AppConfig;
import org.stephen.mapper.SubListMapper;
import org.stephen.model.Request;
import org.stephen.model.Result;
import org.stephen.model.SubList;
import org.stephen.util.HttpRequestUtil;

/**
 * @author qiuwenwei
 */
@RestController
@RequestMapping("wx")
@RequiredArgsConstructor
public class Controller {
    @Autowired
    SubListMapper subListMapper;
    @Autowired
    AppConfig appConfig;

    @GetMapping("get")
    public Result<JSONObject> get(@RequestParam String code) throws Exception {
        String urlStr = "https://finance.pae.baidu.com/selfselect/getstockquotation?all=1&code=" + code + "&isIndex=true&isBk=false&isBlock=false&isFutures=false&isStock=false&newFormat=1&market_type=ab&group=quotation_index_fiveday&finClientType=pc";
        String cookie = "BIDUPSID=B6D5BBDC81F5505D0D65CCEA41974975; PSTM=1659529095; BAIDUID=B276EDBCFE50DB1F72638C5A1279978C:FG=1; BAIDUID_BFESS=B276EDBCFE50DB1F72638C5A1279978C:FG=1; H_WISE_SIDS=60975_60942_61027_61025_61035; H_WISE_SIDS_BFESS=60975_60942_61027_61025_61035; PSINO=3; delPer=0; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; H_PS_PSSID=60942_61027_61035_61054_61098_60851_61130_61127_61114_61135_61141; BA_HECTOR=0h258gakah0hala5aka185a42g7in81jj44lr1u; ZFY=9diHN3aSO2EfxStk9nF6ATghOrQ9svB45N3d6dRsxFc:C; BCLID=11396152004887007453; BCLID_BFESS=11396152004887007453; BDSFRCVID=YatOJexroG33EzoJ-6lMMB7XQAY06Y5TDYLEOwXPsp3LGJLVYKiVEG0Ptoe2l_P-oxIJogKK0eOTHkAF_2uxOjjg8UtVJeC6EG0Ptf8g0M5; BDSFRCVID_BFESS=YatOJexroG33EzoJ-6lMMB7XQ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E0L2/DOo8BSqwaXXEsTu9OxKcnyL+EfhXVKRHSUj5BSXYauQjqMaoayb9NwjQwEd4iFx/O2wQHcK/mh1NuePw==";
        String response = HttpRequestUtil.doGet(urlStr, cookie, token);
        JSONObject object = JSONObject.parseObject(response).getJSONObject("Result");
        JSONArray fivedays = object.getJSONArray("fivedays");
        JSONObject jsonObject = fivedays.getJSONObject(fivedays.size() - 1);
        JSONArray priceinfos = jsonObject.getJSONArray("priceinfos");
// 遍历 priceinfos 数组
        for (int i = 0; i < priceinfos.size(); i++) {
            JSONObject item = priceinfos.getJSONObject(i);
            // 创建一个新的 JSONObject 来存储需要的字段
            JSONObject filteredItem = new JSONObject();
            // 只保留 date_time 和 price 字段
            if (item.containsKey("date_time")) {
                filteredItem.put("date_time", item.get("date_time"));
            }
            if (item.containsKey("price")) {
                filteredItem.put("price", item.get("price"));
            }
            // 替换原始 JSON 对象
            priceinfos.set(i, filteredItem);
        }
        jsonObject.put("priceinfos", priceinfos);
        return new Result<>(jsonObject);
    }

    @GetMapping("getSub")
    public Result<SubList> getSub(@RequestParam String openId) {
        LambdaQueryWrapper<SubList> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SubList::getOpenid, openId);
        lambdaQueryWrapper.eq(SubList::getSubStatus, true);
        SubList subList = subListMapper.selectOne(lambdaQueryWrapper);
        return new Result<>(subList);
    }

    @PostMapping("sub")
    public Result<SubList> sub(@RequestBody Request request) throws Exception {
        String openId = getOpenId(request.getCode());
        LambdaQueryWrapper<SubList> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SubList::getOpenid, openId);
        SubList list = subListMapper.selectOne(lambdaQueryWrapper);
        if (list == null) {
            list = new SubList();
            list.setOpenid(openId);
            list.setSubCode(request.getSubCode());
            list.setSubValue(request.getSubValue());
        }
        list.setSubCode(request.getSubCode());
        list.setSubValue(request.getSubValue());
        list.setSubStatus(request.getSubStatus());
        if (list.getId() != null) {
            subListMapper.updateById(list);
        } else {
            subListMapper.insert(list);
        }
        return new Result<>(list);
    }

    private String getOpenId(String code) throws Exception {
        String urlStr = AppConfig.WECHAT_API_URL + "?appid=" + appConfig.getAppid() + "&secret=" + appConfig.getSecret() +
                "&js_code=" + code + "&grant_type=authorization_code";
        String response = HttpRequestUtil.doGet(urlStr, null, null);
        // 使用抽取的 doGet 方法发送请求
        JSONObject jsonObject = JSONObject.parseObject(response);
        return jsonObject.getString("openid");
    }
}
